package com.fjh.springboot_01.mapper;

import com.fjh.springboot_01.pojo.Friend;
import com.fjh.springboot_01.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface FriendMapper {
    // 检查是否已存在好友请求
    @Select("SELECT * FROM friend WHERE (user_id = #{userId} AND friend_id = #{friendId}) OR (user_id = #{friendId} AND friend_id = #{userId})")
    Friend findFriendshipStatus(int userId, int friendId);

    // 添加好友请求
    @Insert("INSERT INTO friend (user_id, friend_id, status, is_read, message, create_time, update_time) " +
            "VALUES (#{userId}, #{friendId}, 0, false, #{message}, NOW(), NOW())")
    void addFriendRequest(@Param("userId") int userId, @Param("friendId") int friendId, @Param("message") String message);

    // 接受好友请求
    @Update("UPDATE friend SET status = 1, is_read = true, update_time = NOW() WHERE (user_id = #{userId} AND friend_id = #{friendId}) OR (user_id = #{friendId} AND friend_id = #{userId})")
    void acceptFriendRequest(int userId, int friendId);

    // 拒绝好友请求
    @Update("UPDATE friend SET status = 2, is_read = true, update_time = NOW() WHERE (user_id = #{userId} AND friend_id = #{friendId}) OR (user_id = #{friendId} AND friend_id = #{userId})")
    void rejectFriendRequest(int userId, int friendId);

    // 获取用户好友列表
    @Select("SELECT * FROM user WHERE id IN (SELECT friend_id FROM friend WHERE user_id = #{userId} AND status = 1) OR id IN (SELECT user_id FROM friend WHERE friend_id = #{userId} AND status = 1)")
    List<User> findUserFriends(int userId);

    // 删除好友
    @Delete("DELETE FROM friend WHERE ((user_id = #{userId} AND friend_id = #{friendId}) " +
            "OR (user_id = #{friendId} AND friend_id = #{userId})) AND status = 1")
    void deleteFriend(@Param("userId") int userId, @Param("friendId") int friendId);

    // 获取未处理的好友请求通知
    @Select("SELECT f.*, u.username as sender_username, u.user_pic as sender_user_pic " +
            "FROM friend f " +
            "JOIN user u ON f.user_id = u.id " +
            "WHERE f.friend_id = #{userId} AND f.status = 0 " +
            "ORDER BY f.create_time DESC")
    List<Friend> getUnhandledNotifications(int userId);

    // 标记通知为已读
    @Update("UPDATE friend SET is_read = true WHERE id = #{notificationId}")
    void markNotificationAsRead(int notificationId);
}
